package com.evil.common.sso.util;

import com.evil.common.core.constant.AppConstant;
import com.evil.common.core.exception.BusinessException;
import com.evil.common.core.util.ServletUtils;
import com.evil.common.redis.util.RedisUtil;
import com.evil.common.sso.entity.User;
import com.evil.common.sso.enums.RCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 登录用户工具栏
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Slf4j
@Component
public class LoginUtil extends TokenUtil {

    public LoginUtil(RedisUtil redisUtil) {
        super(redisUtil);
    }

    /**
     * 获取登录token
     *
     * @return token
     */
    public Optional<String> isExistLoginToken() {
        String key = AppConstant.TOKEN_KEY;
        HttpServletRequest request = ServletUtils.getRequest();
        String userId = (String) request.getAttribute(key);
        if (StringUtils.isBlank(userId)) {
            userId = request.getParameter(key);
        }
        if (StringUtils.isBlank(userId)) {
            userId = request.getHeader(key);
        }
        return Optional.ofNullable(userId).filter(StringUtils::isNotBlank);
    }

    /**
     * 获取登录token
     *
     * @return token
     */
    public String getLoginToken() {
        return this.isExistLoginToken().orElseThrow(() -> new BusinessException(RCodeEnum.ERROR_UNAUTHENTICATED));
    }

    /**
     * 获取token
     *
     * @return TokenInfo
     */
    public <T extends User> User getLoginUser() {
        return this.getLoginUser(this.getLoginToken());
    }

    /**
     * 获取用户ID
     *
     * @return TokenInfo
     */
    public Long getLoginUserId() {
        return this.getLoginUser().getUserId();
    }


}
